package tony.web.auth.jwt

import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.fasterxml.jackson.core.type.TypeReference
import java.time.Duration
import java.util.Date
import tony.core.utils.convertTo
import tony.core.utils.jsonNode
import tony.core.utils.toDate
import tony.core.utils.toJsonString
import tony.web.auth.IAuthService

/**
 * JwtAuthProvider is
 * @author tangli
 * @date 2025/09/09 09:35
 */
public class JwtAuthService(
    override val expiredIn: Duration,
    private val secret: String,
) : IAuthService<Any> {
    override fun token(params: Any): String {
        val jsonNode =
            params
                .toJsonString()
                .jsonNode()
        return JWT
            .create()
            .withIssuedAt(Date())
            .withExpiresAt(expiredAt().toDate())
            .apply {
                jsonNode.properties().forEach { (key, value) ->
                    when {
                        value.isBoolean -> withClaim(key, value.asBoolean())
                        value.isIntegralNumber -> withClaim(key, value.asLong())
                        value.isFloatingPointNumber -> withClaim(key, value.asDouble())
                        value.isTextual -> withClaim(key, value.asText())
                        value.isArray -> withClaim(key, value.toList())
                        value.isPojo -> withClaim(key, value.convertTo(object : TypeReference<Map<String, Any>>() {}))
                    }
                }
            }.sign(Algorithm.HMAC256(secret))
    }
}
